﻿using Common.Communication;
using DeviceBase.Interfaces;
using DeviceBase.Models;
using Modbus.Core;
using Modbus.Core.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CaiJi.Core.WenDu
{
    public class RSWSN012DModBusRtu : ModbusRtuClient, ICaiJi
    {
        byte Addr;
        public RSWSN012DModBusRtu(string name, int addr, string portName, int baudRate=4800, int timeout = 1500, EndianFormat format = EndianFormat.ABCD, byte stationNumber = 1, bool plcAddresses = false) : base(name, portName, baudRate, timeout, format, stationNumber, plcAddresses)
        {
            Addr = (byte)addr;
        }

        public Result<List<ChuanGanQiResult>> GetValue()
        {
            Result<List<ChuanGanQiResult>> result = new Result<List<ChuanGanQiResult>>();
            AppendInfo(Name, $"读取当前温湿度");
            var re = Read("00", Addr, readLength: 2);
            if (re.IsSucceed == false || re.Value.Length != 4)
            {
                result.IsSucceed = false;
                result.Err = "读取当前温湿度失败";
                AppendResult(Name, result.Err);
                return result.EndTime();
            }
            double wd = (re.Value[0] << 8 + re.Value[1]) / 10.0;
            double sd = (re.Value[2] << 8 + re.Value[3]) / 10.0;
            result.Value.Add(new ChuanGanQiResult() { channel = 1, value = wd, result = wd + "℃" });
            result.Value.Add(new ChuanGanQiResult() { channel = 2, value = sd, result = wd + "%RH" });
            foreach (var item in result.Value)
            {
                AppendInfo(Name, item.result);
            }
            return result.EndTime();
        }

        public Result<bool> SetParameter(params int[] value)
        {
            Result<bool> result = new Result<bool>();
            result.IsSucceed = false;
            result.Err = "暂不支持";
            AppendResult(Name, result.Err);
            return result.EndTime();
        }
    }
}
